import re, sys, os.path

def replace_in_files(arg, dirname, filenames):
    """function useful for replacing text in all files within a directory. Can be used as a callback with os.path.walk.
    Sample usage:
    >>> import os.path
    >>> os.path.walk('/my/dir', replace_in_files, ('regexp_to_find', 'regexp_to_replace'))
    ...
    >>> 
    """
    for fn in filenames:
        fpath = os.path.join(dirname, fn)
        if os.path.isfile(fpath):
            print fpath, '...',
            try:
                f = open(fpath, 'rb')
                txt = f.read()
                f.close()
                txt = re.sub(arg[0], arg[1], txt, re.U)
                f = open(fpath, 'wb')
                f.write(txt)
                f.close()
                print "done."
            except:
                print sys.exc_info()
